package com.ice.body.business.controller;
import com.ice.base.util.BaseUtil;
import com.ice.body.business.model.UserModel;
import com.ice.body.business.service.UserService;
import io.swagger.annotations.ApiOperation;
import com.ice.base.controller.BaseController;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import com.ice.base.result.ResponseResult;
import com.ice.base.result.AjaxResult;
import com.ice.base.result.ResultCodeEnum;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
/**
 * Created with GuoYanBin.
 * Description:
 * Date: 2020-11-18
 * Time: 04:34
 */
@RestController
@ApiIgnore(value = "用户信息")
public class UserController extends BaseController{
    //---------------------------信息-----------------------start
    @Resource
    private UserService userService;
    @Autowired
    private StringRedisTemplate template;

    @ApiOperation(value = "注册")
    @PostMapping("/api_p/User/register")
    public AjaxResult<UserModel> register(UserModel model, @RequestParam("user_name")String user_name, @RequestParam("checkCode")String checkCode) {
        AjaxResult r = ResponseResult.success();
        String redisCode = template.opsForValue().get(model.getUser_name()+"1");
        if(null == redisCode || !redisCode.equals(checkCode)){
            return  ResponseResult.error();
        }
     /*   UserModel exists = userService.selectByUserName(userName);
        if(exists != null){
            return getReturnMap(BaseConstant.Response_MENU.REQUEST_USER_EXISTS);
        }*/
        try{
            if(null != model.getPass_word()){
                String encodePassWord = BaseUtil.getPassword(model.getUser_name(),model.getPass_word());
                model.setPass_word(encodePassWord);
            }else{
                return ResponseResult.error();
            }
            model.init(model);
            //注册 写入用户表
            userService.insert(model);
         /*   String token = JwtUtil.createTokenWithClaim(userName);
            template.opsForValue().set( userName +"token", token, 2, TimeUnit.HOURS);
            returnMap.put("token", token);
            returnMap.put("data", model);*/
        }catch(Exception e){
            e.printStackTrace();
            r = ResponseResult.error();
        }
        return r;
    }

    @ApiOperation(value = "忘记密码提交 更新密码")
    @PostMapping("/api_p/User/forgotPassWord")
    public AjaxResult forgotPassWord(UserModel model , String checkCode) {
        AjaxResult r = ResponseResult.success();
        String redisCode = template.opsForValue().get(model.getUser_name()+"2");
        if(null == redisCode || !redisCode.equals(checkCode)){
            return ResponseResult.errors(ResultCodeEnum.USER_CODE_ERROR.getCode(),ResultCodeEnum.USER_CODE_ERROR.getMessage());
        }
        try{
            if(null != model.getPass_word()){
                String encodePassWord = BaseUtil.getPassword(model.getUser_name(),model.getPass_word());
                model.setPass_word(encodePassWord);
              /*  Integer integer = userService.updateByUserName(model.getUser_name(), encodePassWord);
                if(1 ==integer){
                    template.delete(model.getUserName()+"2");
                }*/
            }else{
                return ResponseResult.error();
            }
        }catch(Exception e){
            e.printStackTrace();
            r=ResponseResult.error();
        }
        return r;
    }

   /* @ApiOperation(value = "密码登陆")
    @PostMapping("/api_p/user/login")
    public Result<String> doLogin(@RequestParam("userName") String userName, @RequestParam("password") String passWord) {
        logger.info(userName+"密码登录！");
        Result r = ResponseResult.success();
        try {
            UserModel model = userService.selectByUserName(userName);
            if(null == model){
                return getReturnMap(BaseConstant.Response_MENU.REQUEST_USER_NOTFOUND);
            }
            String getPassWord = BaseUtils.getPassword(userName,passWord);
            if(!model.getPassWord().equals(getPassWord)){
                throw new IncorrectCredentialsException();
            }
            String token = JwtUtil.createTokenWithClaim(userName);
            returnMap.put("token", token);
            returnMap.put("data",model);
            template.delete(userName+"token");//删除用户已登录的token
            template.opsForValue().set( userName +"token", token, 2, TimeUnit.HOURS);
        } catch (IncorrectCredentialsException ice) {
            return getReturnMap(BaseConstant.Response_MENU.REQUEST_PASSWORD_FAILED);
        } catch (UnknownAccountException uae) {
            return getReturnMap(BaseConstant.Response_MENU.REQUEST_USER_NAME_FAILED);
        } catch (ExcessiveAttemptsException eae) {
            returnMap.put("message", "登录超时!");
        } catch (LockedAccountException lockedAccountException) {
            returnMap.put("message", "用户被冻结!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    @ApiOperation("验证码登录")
    @PostMapping("/api_p/user/codeSign")
    public HashMap codeSign(@RequestParam("userName") String userName, @RequestParam("checkCode") String checkCode) {
        HashMap<String, Object> returnMap = getReturnMap();
        try{
            String redisCode =  template.opsForValue().get(userName+"3");
            if(redisCode == null  || !redisCode.equals(checkCode) ){
                getReturnMap(BaseConstant.Response_MENU.REQUEST_NOTECODE_CHECK_ERROR,returnMap);
                return returnMap;
            }
            UserModel userModel = userService.selectByUserName(userName);
            if (userModel != null) {
                returnMap = signIn(userName);
            }else{
                returnMap.put("message","用户未注册!");
                returnMap.put("status","0");
                returnMap = signIn(userName);
            }
            returnMap.put("data",userModel);
        }catch (Exception e){
            returnMap.put("status","0");
            returnMap.put("message"," 登录失败!");
        }
        return returnMap;
    }
*/
    @ApiOperation(value = "信息-新增")
    @PostMapping("/api/User/insert")
    public AjaxResult<UserModel> insert_User(UserModel model) {
        AjaxResult r = ResponseResult.success();
        try{
            model.init(model);
            Integer count  = userService.insert(model);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();   
        }
        return r;
    }

    @ApiOperation(value = "信息-删除")
    @PostMapping("/api/User/deleteById")
    public AjaxResult<UserModel> deleteById_User(@RequestParam("id") String id) {
        AjaxResult r = ResponseResult.success();
        try{
            Integer count =userService.delete(id);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();   
        }
        return r;
    }

    @ApiOperation(value = "信息-更新")
    @PostMapping("/api/User/updateById")
    public AjaxResult<UserModel> update_User(UserModel model) {
        AjaxResult r = ResponseResult.success();
        try{
            Integer count =userService.update(model);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();   
        }
        return r;
    }

    @ApiOperation(value = "信息-查询一个")
    @PostMapping("/api/User/selectById")
    public AjaxResult<UserModel> selectById_User(@RequestParam("id") String id) {
        AjaxResult r = ResponseResult.success();
        try{
           UserModel model = userService.selectById(id);
           r.setData(model);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();   
        }
        return r;
    }

    @ApiOperation(value = "信息-查询多个")
    @PostMapping("/business/User/selectAll")
    public AjaxResult<UserModel> selectList_User(UserModel model) {
        AjaxResult r = ResponseResult.success();
        try{
           List<UserModel> list = userService.selectListByModel(model);
           r.setData(list);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();   
        }
        return r;
    }

    @ApiOperation(value = "信息-查询分页")
    @PostMapping("/api/User/selectListByPageHelper")
    public AjaxResult<UserModel> selectListByPageHelper_User(@RequestParam(name = "pageSize") Integer pageSize,
                                                             @RequestParam(name = "pageNum") Integer pageNum,
                                                             UserModel model,
                                                             String keyWord){
        AjaxResult r = ResponseResult.success();
        ArrayList list;
        try{
           PageHelper.startPage(pageNum, pageSize);
           if(StringUtils.isEmpty(keyWord)) {
               list = userService.selectListByModel(model);
           } else {
               list = userService.selectListByKeyWord(keyWord);
           }
           r.setData(list);
        }catch (Exception e){
            e.printStackTrace();
            r = ResponseResult.error();   
        }
        return r;
    }
    //---------------------------信息-----------------------end


    /**
     * 登录系统
     *
     * @param userName
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("/loginSys.do")
    public String loginSys(String userName, String password, HttpServletRequest request) {
        // 校验用户信息
 /*       if (com.alibaba.druid.util.StringUtils.isEmpty(userName)) {
            request.setAttribute("message", "账号不能为空");
            return "login";
        }
        if (com.alibaba.druid.util.StringUtils.isEmpty(password)) {
            request.setAttribute("message", "密码不能为空");
            return "login";
        }
        if (!userService.checkUserName(userName)) {
            request.setAttribute("message", "账号不存在");
            return "login";
        }
        if (!userService.checkUserPassword(userName, password)) {
            request.setAttribute("message", "密码错误");
            return "login";
        }
        // 验证通过后查询用户信息
        User paramUser = new User();
        paramUser.setUserName(userName);
        paramUser.setPassword(PasswordUtil.getMd5Password(password));
        User user = userService.searchUserByUserNameAndPassword(paramUser);
        if (user != null) {
            int status = user.getStatus();
            if (status == 1) {
                request.setAttribute("message", "该账号已被禁用");
                return "login";
            }
        }
        // 把用户信息放到session中
        request.getSession().setAttribute("user", user);*/
        // 进入主页
        return "index";
    }
}
